package cn.rocky.pandacodegen.database.mysqlfolder;

import cn.rocky.pandacodegen.common.config.GeneratorConfig;
import cn.rocky.pandacodegen.domain.vo.TableDefinition;
import cn.rocky.pandacodegen.service.TableSelector;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import static cn.rocky.pandacodegen.common.utils.FieldUtil.convertString;

/**
 * 查询mysql数据库表
 *
 * @author rocky
 * @date 2023-06-28
 */
public class MySqlTableSelector extends TableSelector {


    /**
     * mysql 表选择器
     *
     * @param mySqlColumnSelector sql 列选择器
     * @param generatorConfig     配置
     */
    public MySqlTableSelector(MySqlColumnSelector mySqlColumnSelector,
                              GeneratorConfig generatorConfig) {
        super(mySqlColumnSelector, generatorConfig);
    }

    @Override
    protected String getShowTablesSQL(GeneratorConfig generatorConfig) {
        String dbName = generatorConfig.getDbName();
        // check isblank
        if (StringUtils.isBlank(dbName)) throw new RuntimeException("dbName is blank");
        // check special byte
        if (!(dbName.startsWith("`") && dbName.endsWith("`"))) {
            dbName = String.format("`%s`",dbName);
        }
        String sql = "SHOW TABLE STATUS FROM " + dbName;
        if(this.getSchTableNames() != null && this.getSchTableNames().size() > 0) {
            StringBuilder tables = new StringBuilder();
            for (String table : this.getSchTableNames()) {
                tables.append(",'").append(table).append("'");
            }
            sql += " WHERE NAME IN (" + tables.substring(1) + ")";
        }
        return sql;
    }

    @Override
    protected TableDefinition buildTableDefinition(Map<String, Object> tableMap) {
        TableDefinition tableDefinition = new TableDefinition();
        tableDefinition.setTableName(convertString(tableMap.get("NAME")));
        tableDefinition.setComment(convertString(tableMap.get("COMMENT")));
        return tableDefinition;
    }
}
